import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Form, Checkbox, Field, Button, Radio, Balloon, Switch, Message, Input } from '@teamix/ui';
import { Section, Header, Content, YunxiaoIcon, ButtonIcon, Footer } from '@alife/devops-ui';
import { enterPage, Perf } from 'utils/track';
import ListLoading from 'atComponents/ListLoading';
import TagForFeature from 'components/tagForFeature';
import * as actions from '../actions/index';
import docs from 'utils/docs';
import { getFeature } from 'utils/features';
import CloneTooltip from './cloneTootip';
import HistoryModal from './historyModal';
import intl from '../../../../../../../../../locale';

const formItemLayout = {
  labelCol: {
    fixedSpan: 6,
  },

  wrapperCol: {
    span: 16,
  },
};
const roleInfo = getFeature('setting.download_control.allow_role').organization;
const cloneWay = [
  {
    label: 'SSH Clone',
    value: 'ssh-clone',
  },

  {
    label: 'HTTPS Clone',
    value: 'http-clone',
  },

  {
    label: intl.get({
      id: 'code-assets.repositoryPermissions.containers.root.DownloadZipTar',
      defaultMessage: '下载ZIP/TAR',
    }),

    value: 'download',
  },
];

class Root extends Component {
  constructor(props) {
    super(props);
    this.field = new Field(this);
  }

  static propTypes = {
    formSubmit: PropTypes.func,
    getRepoSettingData: PropTypes.func,
  };

  state = {
    loading: true,
    submitting: false,
    disableSaveBtn: true,
    isHistoryModalOpen: false,
    testUrl: '',
    defaultSettings: {},
  };

  componentDidMount() {
    document.title = intl.get({
      id: 'code-assets.repositoryPermissions.containers.root.CodeBaseManagementCloudEffect',
      defaultMessage: '代码库管理 · 云效 Codeup',
    });

    window.onbeforeunload = null;

    this.getData();
    this.props.getOrgAliasName();

    enterPage('Organization-Settings-Repository Permissions', {
      sendPerf: false,
    });
  }

  getData = () => {
    this.props.getRepoSettingData((result) => {
      if (result.repo_creator_identity[0] === 0) {
        result.repo_creator_identity = [15, 60];
      } else if (result.repo_creator_identity[0] === 1) {
        result.repo_creator_identity = [5, 15, 60];
      } else if (result.repo_creator_identity[result.repo_creator_identity.length - 1] !== 60) {
        result.repo_creator_identity.push(60);
      }
      // 代码属主检查
      result.is_commit_check_enable = !!(
        result.repo_push_author_forge_check || result.repo_push_committer_forge_check
      );

      // 属主检查规则
      result.commit_check_rules = [];
      if (result.repo_push_author_forge_check) {
        result.commit_check_rules.push('repo_push_author_forge_check');
      }
      if (result.repo_push_committer_forge_check) {
        result.commit_check_rules.push('repo_push_committer_forge_check');
      }
      result.commit_check_level =
        result.repo_push_author_forge_check || result.repo_push_committer_forge_check;

      // 代码克隆下载控制添加默认数据
      this.initCloneDownloadData(result);

      // 初始化prehook数据
      this.initPrehookData(result);

      this.field.setValues(result);

      this.setState({
        loading: false,
        defaultSettings: result,
      });
    });
  };

  testPrehook = () => {
    const testUrl = this.field.getValue('third_party_url');
    if (!testUrl) {
      return;
    }
    this.setState({ isHistoryModalOpen: true, testUrl });
  };

  initPrehookData = (result) => {
    const { org_push_rule } = result;
    // 当前返回最多只有一条
    if (org_push_rule && org_push_rule.length) {
      const { rule_infos = [] } = org_push_rule[0];
      result.is_prehook_enable = true;
      result.prehook_checker_type = rule_infos[0] ? rule_infos[0].checker_type : '';
      result.third_party_url = rule_infos[0] ? rule_infos[0].third_party_url : '';
    } else {
      result.is_prehook_enable = false;
    }
  };

  formChange = () => {
    let changed = false;
    const fieldNames = this.field.getNames();
    for (let i = 0; i < fieldNames.length; i++) {
      const name = fieldNames[i];
      const defaultSetting = this.state.defaultSettings[name];
      const nowSetting = this.field.getValue(name);
      if (defaultSetting instanceof Array && nowSetting instanceof Array) {
        if (defaultSetting.sort().toString() !== nowSetting.sort().toString()) {
          changed = true;
        }
      } else if (typeof defaultSetting === 'boolean') {
        if (nowSetting === undefined) {
          changed = defaultSetting === true;
        } else {
          changed = defaultSetting !== nowSetting;
        }
      } else {
        changed = defaultSetting !== nowSetting;
      }
      if (changed === true) {
        break;
      }
    }
    this.setState({
      disableSaveBtn: !changed,
    });

    if (changed) {
      window.onbeforeunload = function () {
        return intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.AreYouSureYouWant',
          defaultMessage: '确定离开此页面？',
        });
      };
    } else {
      window.onbeforeunload = null;
    }
  };

  initCloneDownloadData = (result) => {
    const defaultRoleList = [];
    const defaultMethodList = [];
    const next_role_list = result.org_clone_download_role_list || [];
    const next_method_list = result.org_clone_download_method_list || [];
    next_role_list.forEach((item) => {
      if (item.allowed) {
        defaultRoleList.push(item.role_code);
      }
    });
    next_method_list.forEach((item) => {
      if (item.allowed) {
        defaultMethodList.push(item.permission_code);
      }
    });

    result.role_list = defaultRoleList;
    result.method_list = defaultMethodList;
  };

  // 处理下载控制数据
  addCloneDownloadInfoToFormData = (formData) => {
    const { org_clone_download_method_list = [], org_clone_download_role_list = [] } =
      this.state.defaultSettings;

    if (formData.open_clone_download_control) {
      if (formData.role_list) {
        formData.org_clone_download_role_list = org_clone_download_role_list.map((item) => {
          return {
            role_code: item.role_code,
            allowed: formData.role_list.includes(item.role_code),
          };
        });
      }

      if (formData.method_list) {
        formData.org_clone_download_method_list = org_clone_download_method_list.map((item) => {
          return {
            permission_code: item.permission_code,
            allowed: formData.method_list.includes(item.permission_code),
          };
        });
      }
    } else {
      formData.org_clone_download_method_list = [];
      formData.org_clone_download_role_list = [];
    }

    delete formData.role_list;
    delete formData.method_list;
  };

  roleValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    const method_list = this.field.getValue('method_list');
    if (value && value.length && !method_list.length) {
      this.field.setError(
        'method_list',
        intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.GouXuanTheAllowedMethod',
          defaultMessage: '请勾选允许的方式',
        }),
      );
    } else {
      this.field.setError('method_list', '');
    }
    callback();
  };

  methodValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    const role_list = this.field.getValue('role_list');
    if (role_list && role_list.length && !value.length) {
      callback(
        intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.GouXuanTheAllowedMethod',
          defaultMessage: '请勾选允许的方式',
        }),
      );

      return;
    }
    callback();
  };

  deleteCloneDownloadKey = (formData) => {
    const { defaultSettings } = this.state;
    try {
      const isControlSame =
        formData.open_clone_download_control === defaultSettings.open_clone_download_control;
      let changedListLength = 0;
      const form_method_list = formData.org_clone_download_method_list;
      const form_role_list = formData.org_clone_download_role_list;
      const default_method_list = defaultSettings.org_clone_download_method_list;
      const default_role_list = defaultSettings.org_clone_download_role_list;

      form_method_list.forEach((item1) => {
        default_method_list.forEach((item2) => {
          if (item2.permission_code === item1.permission_code && item2.allowed !== item1.allowed) {
            changedListLength += 1;
          }
        });
      });
      form_role_list.forEach((item1) => {
        default_role_list.forEach((item2) => {
          if (item2.role_code === item1.role_code && item2.allowed !== item1.allowed) {
            changedListLength += 1;
          }
        });
      });

      if (isControlSame && !changedListLength) {
        delete formData.open_clone_download_control;
        delete formData.org_clone_download_method_list;
        delete formData.org_clone_download_role_list;
      }
    } catch (e) {
      console.error(e);
    }
  };

  // org_push_rule：id 是否为 null，来区分创建和修改
  // deleted_org_push_rule_id 字段：根据是否为 null，来区分删除，传入 push rule id 即可
  handleRehookData = (formData) => {
    const { is_prehook_enable, prehook_checker_type, third_party_url } = formData;
    const { defaultSettings } = this.state;
    if (is_prehook_enable) {
      formData.org_push_rule = {
        id:
          defaultSettings.org_push_rule && defaultSettings.org_push_rule[0]
            ? defaultSettings.org_push_rule[0].id
            : null,
        ref_type: 'Branch',
        ref_name: '**',
        rule_infos: [
          {
            checker_name: 'ThirdPartyChecker',
            extra_message: '',
            checker_type: prehook_checker_type,
            third_party_url,
            third_party_timeout: '1000',
          },
        ],
      };

      delete formData.deleted_org_push_rule_id;
    } else {
      formData.deleted_org_push_rule_id =
        defaultSettings.org_push_rule && defaultSettings.org_push_rule[0]
          ? defaultSettings.org_push_rule[0].id
          : null;
      delete formData.org_push_rule;
    }
    delete formData.prehook_checker_type;
    delete formData.third_party_url;
    delete formData.is_prehook_enable;
  };

  URLValidator = (rule, value, callback) => {
    if (!value) {
      callback();
      return;
    }
    if (!/(https?|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/.test(value)) {
      callback(
        intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.TheUrlParameterIsInvalid',
          defaultMessage: 'URL 参数不合法',
        }),
      );

      return;
    }
    callback();
  };

  handleSave = () => {
    if (this.state.submitting) return;
    this.setState({ submitting: true });
    this.field.validate((errors) => {
      if (!errors) {
        const formData = this.field.getValues();
        const { commit_check_rules, is_commit_check_enable, commit_check_level } = formData;
        // 先全部置空
        formData.repo_push_author_forge_check = '';
        formData.repo_push_committer_forge_check = '';
        if (is_commit_check_enable) {
          commit_check_rules &&
            commit_check_rules.forEach((item) => {
              formData[item] = commit_check_level || '';
            });
        }

        delete formData.is_commit_check_enable;
        delete formData.commit_check_rules;
        delete formData.commit_check_level;

        // 下载克隆控制处理
        this.addCloneDownloadInfoToFormData(formData);
        // open_clone_download_control 传给后端，如果没修改不传，否则会额外多出日志
        this.deleteCloneDownloadKey(formData);
        // fix 防止后端重复触发多余敏感行为日志
        delete formData.is_sensitive_behavior_enable;

        if (getFeature('organization.setting.project.push_rules.third_party')) {
          this.handleRehookData(formData);
        }

        this.props.formSubmit(formData, () => {
          this.setState({
            submitting: false,
            disableSaveBtn: true,
          });

          this.getData();
          window.onbeforeunload = null;
        });
      } else {
        this.setState({ submitting: false });
      }
    });
  };

  repoVisibilityValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  repoAdminAccessVisibilityLevelValidator = (rule, value, callback) => {
    if (value && value.length > 0) {
      callback();
    } else {
      callback(
        intl.get({
          id: 'code-assets.repositoryPermissions.containers.root.SelectAtLeastOne',
          defaultMessage: '该项至少选中一个',
        }),
      );
    }
  };

  disableWebide = (data) => {
    const flag =
      data && data.length > 0 && data.filter((va) => va === 'ssh-clone' || va === 'http-clone');
    return !flag.length;
  };

  render() {
    const { field } = this;
    const { init } = field;
    const { isAliasNameSuccess } = this.props;
    const { isHistoryModalOpen, testUrl } = this.state;

    const { open_clone_download_control, clone_download_control_gray } = this.state.defaultSettings;

    // 云上内测
    const is_clone_download_switch_disabled = !clone_download_control_gray;

    return (
      <>
        {this.state.loading ? (
          <ListLoading />
        ) : (
          <>
            {isAliasNameSuccess && (
              <>
                <Header
                  title={intl.get({
                    id: 'code-assets.repositoryPermissions.containers.root.CodeLibrarySettings',
                    defaultMessage: '代码库设置',
                  })}
                />

                <Content>
                  <div>
                    <Form
                      {...formItemLayout}
                      labelAlign="top"
                      labelTextAlign="right"
                      className="settings-repos-form"
                      field={field}
                      onChange={this.formChange}
                    >
                      <Section
                        title={intl.get({
                          id: 'code-assets.repositoryPermissions.containers.root.CreateACodeLibrary',
                          defaultMessage: '创建代码库',
                        })}
                      >
                        <Form.Item
                          label={intl.get({
                            id: 'code-assets.repositoryPermissions.containers.root.Role',
                            defaultMessage: '角色',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox.Group
                            className="settings-repos-checkgroup"
                            {...init('repo_creator_identity')}
                          >
                            <Checkbox value={60} disabled>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.EnterpriseAdministrator',
                                defaultMessage: '企业管理员',
                              })}
                            </Checkbox>
                            <Checkbox value={15}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.EnterpriseMember',
                                defaultMessage: '企业成员',
                              })}
                            </Checkbox>
                            <Checkbox value={5}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.ExternalMembersOfTheEnterprise',
                                defaultMessage: '企业外部成员',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                        <Form.Item
                          label={intl.get({
                            id: 'code-assets.repositoryPermissions.containers.root.Openness',
                            defaultMessage: '公开性',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox.Group
                            className="settings-repos-checkgroup"
                            itemDirection="ver"
                            {...init('repo_visibility_level', {
                              rules: [
                                {
                                  validator: this.repoVisibilityValidator,
                                },
                              ],
                            })}
                          >
                            <Checkbox value={0}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.AllowPrivate',
                                defaultMessage: '允许私有',
                              })}

                              <span className="settings-repos-form-tips">
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.OnlyMembersOfTheCode',
                                  defaultMessage: '仅代码库成员可访问',
                                })}
                              </span>
                            </Checkbox>
                            <Checkbox value={10}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.AllowEnterpriseVisibility',
                                defaultMessage: '允许企业可见',
                              })}

                              <span className="settings-repos-form-tips">
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.EnterpriseMembersCanAccess',
                                  defaultMessage: '企业内成员可访问',
                                })}
                              </span>
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>

                      <Section
                        title={intl.get({
                          id: 'code-assets.repositoryPermissions.containers.root.AdjustDatabasePublicity',
                          defaultMessage: '调整库公开性',
                        })}
                      >
                        <Form.Item>
                          <Checkbox.Group
                            itemDirection="ver"
                            className="settings-repos-checkgroup"
                            {...init('repo_admin_access_visibility_level', {
                              rules: [
                                {
                                  validator: this.repoAdminAccessVisibilityLevelValidator,
                                },
                              ],
                            })}
                          >
                            <Checkbox value={0}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.AllowTheDatabaseAdministratorTo',
                                defaultMessage: '允许库管理员调整公开性为私有',
                              })}
                            </Checkbox>
                            <Checkbox value={10}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.AllowDatabaseAdministratorsToAdjust',
                                defaultMessage: '允许库管理员调整公开性为企业可见',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>

                      <Section
                        title={intl.get({
                          id: 'code-assets.repositoryPermissions.containers.root.PushPullCode',
                          defaultMessage: '推拉代码',
                        })}
                      >
                        <Form.Item
                          label={
                            <div style={{ position: 'relative' }}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.CloneDownloadControl',
                                defaultMessage: '克隆下载控制',
                              })}
                              <TagForFeature
                                type="primary"
                                size="small"
                                tagText="BETA"
                              />
                            </div>
                          }
                          labelTextAlign="left"
                          style={{ marginBottom: 0 }}
                        >
                          <div className="enterprise-repo-setting-clone-switch">
                            <div className="switch-left">
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.YouCanOnlyCloneAnd',
                                defaultMessage:
                                  '限制代码库的克隆下载操作，开启后仅允许通过勾选的方式进行克隆下载，以增强企业数据安全性。',
                              })}
                            </div>
                            {getFeature('organization.setting.project.clone_download_control.need_apply') ?
                              <CloneTooltip
                                // 集团内全部开放、云上内测
                                disabled={is_clone_download_switch_disabled}
                                trigger={
                                  <Switch
                                    name="switch"
                                    disabled={is_clone_download_switch_disabled}
                                    checked={this.field.getValue('open_clone_download_control')}
                                    {...init('open_clone_download_control', {
                                      initValue: open_clone_download_control,
                                    })}
                                  />
                                }
                              />
                              :
                              <Switch
                                name="switch"
                                disabled={is_clone_download_switch_disabled}
                                checked={this.field.getValue('open_clone_download_control')}
                                {...init('open_clone_download_control', {
                                  initValue: open_clone_download_control,
                                })}
                              />
                            }
                          </div>
                        </Form.Item>

                        <Form.Item
                          className=""
                          style={{
                            marginBottom: 4,
                            display: this.field.getValue('open_clone_download_control')
                              ? 'block'
                              : 'none',
                          }}
                        >
                          <div className="enterprise-repo-setting-clone-detail">
                            <div className="detail-label">
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.RolesAllowed',
                                defaultMessage: '允许的角色',
                              })}
                            </div>
                            <CloneTooltip
                              trigger={
                                <Checkbox.Group
                                  itemDirection="hoz"
                                  {...init('role_list', {
                                    initValue: [],
                                    rules: [
                                      {
                                        validator: this.roleValidator,
                                      },
                                    ],
                                  })}
                                >
                                  {roleInfo.map((item) => {
                                    return (
                                      <Checkbox value={item.value} disabled={item.disabled} key={item.value}>
                                        {item.label}
                                      </Checkbox>
                                    );
                                  })}
                                </Checkbox.Group>
                              }
                            />
                          </div>
                        </Form.Item>

                        <Form.Item
                          className=""
                          style={{
                            marginBottom: 0,
                            display: this.field.getValue('open_clone_download_control')
                              ? 'block'
                              : 'none',
                          }}
                        >
                          <div className="enterprise-repo-setting-clone-detail">
                            <div className="detail-label">
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.ValidValues',
                                defaultMessage: '允许的方式',
                              })}
                            </div>
                            <CloneTooltip
                              trigger={
                                <Checkbox.Group
                                  itemDirection="hoz"
                                  {...init('method_list', {
                                    initValue: [],
                                    rules: [
                                      {
                                        validator: this.methodValidator,
                                      },
                                    ],
                                  })}
                                >
                                  {cloneWay.map((item) => {
                                    return (
                                      <Checkbox value={item.value} key={item.value}>
                                        {item.label}
                                      </Checkbox>
                                    );
                                  })}
                                </Checkbox.Group>
                              }
                            />
                          </div>
                          {this.field.getState('method_list') === 'error' ? (
                            <div className="enterprise-repo-setting-clone-help error">
                              <YunxiaoIcon type="delete-fill" />
                              <span className="next-form-item-help-text">
                                {this.field.getError('method_list')}
                              </span>
                            </div>
                          ) : (
                            <div className="enterprise-repo-setting-clone-help">
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.ThisRestrictionDoesNotInclude',
                                defaultMessage: '* 该克隆方式限制范围不包括 Flow 流水线中的使用',
                              })}
                            </div>
                          )}
                          {this.disableWebide(this.field.getValue('method_list')) && (
                            <Message type="warning" style={{ maxWidth: 500, alignItems: 'center' }}>
                              同时限制 SSH 和 HTTPS Clone 时，将禁用 WebIDE
                            </Message>
                          )}
                        </Form.Item>

                        {is_clone_download_switch_disabled && (
                          <Form.Item
                            {...init('is_download_enable')}
                            label={intl.get({
                              id: 'code-assets.repositoryPermissions.containers.root.DownloadControl',
                              defaultMessage: '下载控制',
                            })}
                            labelTextAlign="left"
                          >
                            <Checkbox checked={this.field.getValue('is_download_enable')}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.ZipTarPackageDownloadAllowed',
                                defaultMessage: '允许打包下载 ZIP / TAR',
                              })}
                            </Checkbox>
                          </Form.Item>
                        )}

                        <Form.Item
                          {...init('is_force_push_forbidden')}
                          label={intl.get({
                            id: 'code-assets.repositoryPermissions.containers.root.PushRules',
                            defaultMessage: '推送规则',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox checked={this.field.getValue('is_force_push_forbidden')}>
                            <span style={{ position: 'relative' }}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.ForcePushProhibitedForcePush',
                                defaultMessage: '禁止强制推送（Force Push）',
                              })}

                              <Balloon.Tooltip
                                trigger={
                                  <ButtonIcon
                                    text
                                    name="question-line"
                                    style={{
                                      marginLeft: '-4px',
                                      position: 'absolute',
                                      top: '-2px',
                                    }}
                                  />
                                }
                                popupStyle={{
                                  maxWidth: 'none',
                                  width: 430,
                                }}
                                align="t"
                              >
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.AfterThisFeatureIsEnabled',
                                  defaultMessage:
                                    '开启后企业所有仓库将不允许使用 git push -f 强制修改提交历史',
                                })}
                              </Balloon.Tooltip>
                            </span>
                          </Checkbox>
                        </Form.Item>
                        <Form.Item
                          {...init('is_commit_check_enable', {
                            props: {
                              onChange: (value) => {
                                if (value) {
                                  this.field.setValue('commit_check_level', 'warn');
                                  this.field.setValue('commit_check_rules', [
                                    'repo_push_author_forge_check',
                                  ]);
                                } else {
                                  this.field.setValue('commit_check_level', '');
                                  this.field.setValue('commit_check_rules', []);
                                }
                              },
                            },
                          })}
                          label=""
                          labelTextAlign="left"
                        >
                          <Checkbox checked={this.field.getValue('is_commit_check_enable')}>
                            <span style={{ position: 'relative' }}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.TheCodeBelongsToThe',
                                defaultMessage: '代码属主检查',
                              })}

                              <Balloon
                                type="normal"
                                trigger={
                                  <ButtonIcon
                                    text
                                    name="question-line"
                                    style={{ marginLeft: 4, position: 'absolute', top: '-2px' }}
                                  />
                                }
                                align="t"
                              >
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.CheckWhetherTheEmailInformation',
                                  defaultMessage:
                                    '检查代码作者或者提交者邮箱信息是否与当前用户主邮箱一致。',
                                })}
                                <a target="_blank" href={docs('commit-check-org')} rel="noreferrer">
                                  {intl.get({
                                    id: 'code-assets.repositoryPermissions.containers.root.HowToUse',
                                    defaultMessage: '如何使用',
                                  })}
                                </a>{' '}
                                ？
                              </Balloon>
                            </span>
                          </Checkbox>
                        </Form.Item>
                        {this.field.getValue('is_commit_check_enable') && (
                          <>
                            <Form.Item label={''} labelAlign="left" style={{ marginBottom: 4 }}>
                              <span>
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.CheckRules',
                                  defaultMessage: '检查规则：',
                                })}
                              </span>
                              <Checkbox.Group
                                className="settings-repos-checkgroup"
                                {...init('commit_check_rules', {
                                  rules: [
                                    {
                                      validator: this.repoVisibilityValidator,
                                    },
                                  ],
                                })}
                              >
                                <Checkbox value={'repo_push_author_forge_check'}>
                                  {intl.get({
                                    id: 'code-assets.repositoryPermissions.containers.root.CheckAuthorAuthor',
                                    defaultMessage: '检查作者（Author）',
                                  })}
                                </Checkbox>
                                <Checkbox value={'repo_push_committer_forge_check'}>
                                  {intl.get({
                                    id: 'code-assets.repositoryPermissions.containers.root.CheckSubmitterCommitter',
                                    defaultMessage: '检查提交者（Committer）',
                                  })}
                                </Checkbox>
                              </Checkbox.Group>
                            </Form.Item>
                            <Form.Item label={''} labelAlign="left">
                              <span>
                                {intl.get({
                                  id: 'code-assets.repositoryPermissions.containers.root.Limits',
                                  defaultMessage: '限制级别：',
                                })}
                              </span>
                              <Radio.Group
                                className="settings-repos-checkgroup"
                                {...init('commit_check_level', {})}
                              >
                                <Radio value={'block'}>
                                  {intl.get({
                                    id: 'code-assets.repositoryPermissions.containers.root.NoPush',
                                    defaultMessage: '禁止推送',
                                  })}
                                </Radio>
                                <Radio value={'warn'}>
                                  {intl.get({
                                    id: 'code-assets.repositoryPermissions.containers.root.WarningOnlyPushAllowed',
                                    defaultMessage: '仅警告，允许推送',
                                  })}
                                </Radio>
                              </Radio.Group>
                            </Form.Item>
                          </>
                        )}
                        {/* 三方系统验证 */}
                        {getFeature('organization.setting.project.push_rules.third_party') ?
                          <>
                            <Form.Item
                              label=""
                              labelTextAlign="left"
                              {...init('is_prehook_enable', {
                                props: {
                                  onChange: (value) => {
                                    if (value) {
                                      this.field.setValue('prehook_checker_type', 'warn');
                                      this.field.setValue('third_party_url', '');
                                    } else {
                                      this.field.setValue('prehook_checker_type', '');
                                      this.field.setValue('third_party_url', '');
                                    }
                                  },
                                },
                              })}
                            >
                              <Checkbox checked={this.field.getValue('is_prehook_enable')}>
                                <span style={{ position: 'relative' }}>
                                  三方系统验证
                                  <Balloon
                                    closable={false}
                                    trigger={
                                      <ButtonIcon
                                        name="question-line"
                                        style={{ marginLeft: 4, position: 'absolute', top: '-2px' }}
                                      />
                                    }
                                    align="t"
                                  >
                                    <a target="_blank" href={docs('third-confirm')} rel="noreferrer">如何使用三方系统验证？</a>
                                  </Balloon>
                                </span>
                              </Checkbox>
                            </Form.Item>
                            {this.field.getValue('is_prehook_enable') && (
                              <React.Fragment>
                                <Form.Item label={''} labelAlign="left">
                                  <div style={{ display: 'flex', alignItems: 'center' }}>
                                    <span style={{ marginRight: 24 }}>URL 地址：</span>
                                    <Input
                                      placeholder="请输入三方系统地址"
                                      className="prehook-url"
                                      {...this.field.init('third_party_url', {
                                        initValue: '',
                                        rules: [
                                          {
                                            required: true,
                                            message: '该项为必填项',
                                          },

                                          {
                                            validator: this.URLValidator,
                                          },
                                        ],
                                      })}
                                    />

                                    <Button
                                      type="primary"
                                      className="test-prehook-btn"
                                      onClick={this.testPrehook}
                                      style={{ marginLeft: 24 }}
                                    >
                                      测试链接
                                    </Button>
                                  </div>
                                </Form.Item>
                                <Form.Item label={''} labelAlign="left">
                                  <span style={{ position: 'relative', top: '2px' }}>
                                    异常处理
                                    <Balloon.Tooltip
                                      type="normal"
                                      trigger={
                                        <ButtonIcon
                                          name="information-line"
                                          style={{ position: 'relative', top: '-2px' }}
                                        />
                                      }
                                      align="t"
                                    >
                                      设置三方系统返回异常的处理，其中超时时间默认 1 秒
                                    </Balloon.Tooltip>
                                    ：
                                  </span>
                                  <Radio.Group
                                    className="settings-repos-checkgroup"
                                    {...this.field.init('prehook_checker_type', {})}
                                  >
                                    <Radio value={'block'}>验证不通过</Radio>
                                    <Radio value={'warn'}>忽略规则，验证通过</Radio>
                                  </Radio.Group>
                                </Form.Item>
                              </React.Fragment>
                            )}
                          </>
                          :
                          null
                        }
                      </Section>

                      <Section
                        title={intl.get({
                          id: 'code-assets.repositoryPermissions.containers.root.GroupOptions',
                          defaultMessage: '组选项',
                        })}
                      >
                        <Form.Item
                          {...init('is_group_required')}
                          label={intl.get({
                            id: 'code-assets.repositoryPermissions.containers.root.CodeGroup',
                            defaultMessage: '代码组',
                          })}
                          labelTextAlign="left"
                        >
                          <Checkbox checked={this.field.getValue('is_group_required')}>
                            {intl.get({
                              id: 'code-assets.repositoryPermissions.containers.root.RequiredCodeGroup',
                              defaultMessage: '必选代码组',
                            })}
                          </Checkbox>
                        </Form.Item>
                      </Section>

                      <Section
                        title={intl.get({
                          id: 'code-assets.repositoryPermissions.containers.root.DeleteACodeLibrary',
                          defaultMessage: '删除代码库',
                        })}
                      >
                        <Form.Item>
                          <Checkbox.Group
                            itemDirection="ver"
                            className="settings-repos-checkgroup"
                            {...init('repo_admin_operation')}
                          >
                            <Checkbox value={1}>
                              {intl.get({
                                id: 'code-assets.repositoryPermissions.containers.root.AllowDatabaseAdministratorsToDelete',
                                defaultMessage: '允许库管理员删除代码库',
                              })}
                            </Checkbox>
                          </Checkbox.Group>
                        </Form.Item>
                      </Section>
                    </Form>
                  </div>
                </Content>
                <Footer
                  left={
                    <Button
                      loading={this.state.submitting}
                      type="primary"
                      onClick={this.handleSave}
                      disabled={this.state.disableSaveBtn}
                    >
                      {intl.get({
                        id: 'code-assets.repositoryPermissions.containers.root.Save',
                        defaultMessage: '保存',
                      })}
                    </Button>
                  }
                />
              </>
            )}

            {isHistoryModalOpen && (
              <HistoryModal
                isModalOpen={isHistoryModalOpen}
                testUrl={testUrl}
                closeModal={() => {
                  this.setState({
                    isHistoryModalOpen: false,
                    testUrl: '',
                  });
                }}
              />
            )}

            <Perf page="Organization-Settings-Repository Permissions" />
          </>
        )}
      </>
    );
  }
}

export default connect(
  (state) => state.organization.settings.repositoryPermissions,
  (dispatch) => bindActionCreators(actions, dispatch),
)(Root);
